package console

import (
	"bufio"
	"leaf/core/log"
	"leaf/core/tool"
	"os"
	"strings"
)

var reader = bufio.NewReader(os.Stdin)
var commands = map[string]func(args ...string){}
var commandChan = make(chan string, 64)

func Register(command string, commandFunc func(args ...string)) {
	commands[command] = commandFunc
}

func run() {
	var lineStr string
	go func() {
		for {
			bytes, _, err := reader.ReadLine()
			if err != nil {
				break
			}

			line := string(bytes)
			if line == "" {
				continue
			}

			commandChan <- line
		}

	}()

	for {
		select {
		case <-tool.GoSigChan():
			goto STOP
		case lineStr = <-commandChan:
			if len(lineStr) > 0 {
				lineStr = strings.TrimSuffix(lineStr[:len(lineStr)-1], "\r")
				contents := strings.Fields(lineStr)
				if len(contents) < 2 {
					continue
				}
				command := contents[0]
				args_strings := contents[1:]
				args := make([]string, len(args_strings))
				for k, v := range args_strings {
					args[k] = v
				}

				if commandFunc, ok := commands[command]; ok {
					commandFunc(args...)
				} else {
					log.Error("command <%v> not find", command)
				}
			}
		}
	}
STOP:
}

func Start() {
	tool.Go(run)
}

func Destroy() {
	tool.Try(func() {
		close(commandChan)
		os.Stdin.Close()
	}, nil)
}
